//
//  SiMiViewController.m
//  jingdongfang
//
//  Created by 郝志宇 on 16/7/11.
//  Copyright © 2016年 XuDong Jin. All rights reserved.
//

#import "SiMiViewController.h"
#import "ZuoPinCell.h"
#import "XiangQingViewController.h"
#import "FindLayout.h"
#import "IGGetUploadApi.h"
#import "IGdeletWorksApi.h"
#import "IGiGalleryListApi.h"
#import "IGiGalleryPushApi.h"
#import "IGPushiGalleryListVC.h"
#import "MyArtViewController.h"
#import "UpPrintVC.h"
#import "BatchUploadVC.h"

@interface SiMiViewController () <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout> {
    
    UICollectionView *collect;
    UIButton *meBtn;
    
    NSMutableArray *selArr;
    BOOL isEdit;
    UIView *tabbar;
    UIView *nonView;
    
    NSString *p_idsStr;
    NSString *pay_type;
    NSMutableArray *imageUrlArr;
    NSString *uId;
    NSString *secrecy;//1公开, 2保密
    NSInteger pageNumber;//页数，从0开始
    NSString *queryTime;//查询时间
    IGArtWorkModel *info ;
    MyArtViewController *v1;
    NSString *pushSuccess;
}
@property(nonatomic,strong)IGGetUploadApi *simiApi;
@property (nonatomic, strong)NSMutableArray *simiDataArr;
@property(nonatomic,strong)IGdeletWorksApi *deletApi;
@property (nonatomic, strong) IGiGalleryListApi *igalleryListApi;
@property (nonatomic, strong) NSArray *iGalleryListArr;
@end

@implementation SiMiViewController
#pragma mark -懒加载
-(NSMutableArray *)simiDataArr
{
    if(!_simiDataArr)
    {
        _simiDataArr=[NSMutableArray array];
    }
    return _simiDataArr;
}
#pragma mark -生命周期
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor c2Color];
    meBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    meBtn.frame=CGRectMake(15, 15, KSCREENWIDTH-30, 40);
    meBtn.clipsToBounds=YES;
    meBtn.layer.borderWidth=1.0f;
    meBtn.layer.cornerRadius=5.f;
    meBtn.layer.borderColor=[UIColor c1Color].CGColor;
    meBtn.titleLabel.font=[UIFont font14];
//    [meBtn setTitle:@"上传私密作品" forState:UIControlStateNormal];
    [meBtn setTitle:NSLocalizedString(@"Upload Private Works", nil) forState:UIControlStateNormal];
    [meBtn setTitleColor:[UIColor c1Color] forState:UIControlStateNormal];
    meBtn.userInteractionEnabled=YES;
    [meBtn addTarget:self action:@selector(mePhoto) forControlEvents:UIControlEventTouchUpInside];
    
    FindLayout *layout = [[FindLayout alloc] init];
    collect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT-NavigationMagin-44-20) collectionViewLayout:layout];
    collect.backgroundColor = [UIColor clearColor];
    collect.delegate = self;
    collect.dataSource = self;
    if (@available(iOS 11.0, *)) {
        collect.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        collect.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
        collect.scrollIndicatorInsets = collect.contentInset;
    }
    collect.alwaysBounceVertical = YES;
    [collect registerClass:[ZuoPinCell class] forCellWithReuseIdentifier:@"siMiArtCell"];
    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTap:)];
    [collect addGestureRecognizer:longTap];
    
    nonView=[[UIView alloc]initWithFrame:CGRectMake(0, 60, KSCREENWIDTH, 100)];
    nonView.backgroundColor=[UIColor clearColor];
    UILabel *nonLable=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 60)];
    nonLable.center=nonView.center;
//    nonLable.text=@"您还没有上传任何私密作品\n快去上传吧~";
    nonLable.text=NSLocalizedString(@"No private artworks uploaded yet. Go upload now.", nil);
    nonLable.numberOfLines=2;
    nonLable.textAlignment=NSTextAlignmentCenter;
    nonLable.font=[UIFont font16];
    nonLable.textColor=[UIColor blackColor];
    [nonView addSubview:nonLable];
    nonView.hidden=YES;
    collect.top= meBtn.bottom+10;
    [collect addSubview:nonView];
    [self.view addSubview:meBtn];
    [self.view addSubview:collect];
    self.simiApi = [IGGetUploadApi new];
    [self firstPage];
    [self requestIGlist];
    @KWeakObj(self)
    [collect ig_setHeaderWithRefreshingBlock:^{
        [selfWeak firstPage];
    }];
}

- (void)firstPage
{
    secrecy=@"2";
    pageNumber = 0;
    queryTime = @"";
    [self requestData];
}
- (void)scrollToTOP
{
    if ([pushSuccess isEqualToString:@"1"]) {
        if (isEdit) {
            [self canel];
            self.editBlock(NO);
        }
        pushSuccess=@"0";
    }
   
    [collect setContentOffset:CGPointMake(0, 0) animated:YES];
}
-(void)requestData
{
    __weak typeof(self) weakSelf = self;
    self.simiApi.secrecy = secrecy;
    self.simiApi.pageNumber = pageNumber;
    self.simiApi.queryTime = queryTime;
    [self.simiApi startWithDecodeClass:[IGGetUploadResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        [collect ig_endHeaderRefreshing];
        [collect ig_endFooterRefreshing];
        if (responseObject)
        {
            IGGetUploadResp *resp = responseObject;
            IGGetUploadModel *model = resp.data;
            NSArray *tmpArr = model.lstWork;
            queryTime = model.queryTime;
            if (tmpArr && tmpArr.count > 0)
            {
                [weakSelf setupFooter];
            }
            if (pageNumber == 0)
            {
                _simiDataArr = [NSMutableArray arrayWithArray:tmpArr];
                if (_simiDataArr.count == 0)
                {
                    nonView.hidden=NO;
                    tabbar.hidden=YES;
                    [collect ig_removeFooterRefreshing];
                }
            }else
            {
                if (model.lstWork.count==0)
                {
                    [collect ig_endFooterRefreshingWithNoMoreData];
                }
                [_simiDataArr addObjectsFromArray:model.lstWork];
                for (int i=0; i<model.lstWork.count; i++) {
                    [selArr addObject:@(NO)];
                }
            }
            [collect reloadData];
        }
        else
        {
        }
    }];
    
}
- (void)setupFooter
{
    @KWeakObj(self)
    [collect ig_setFooterWithRefreshingBlock:^{
        pageNumber++;
//        if (isEdit) {
//            [self canel];
//        }
//        self.editBlock(NO);
        [selfWeak requestData];
    }];
}


#pragma mark - UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _simiDataArr.count ? : 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZuoPinCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"siMiArtCell" forIndexPath:indexPath];
    cell.data = _simiDataArr[indexPath.item];
    cell.isEdit = isEdit;
    if (isEdit) {
        cell.isSel = [selArr[indexPath.item] boolValue];
    }
    [cell setNeedsLayout];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (isEdit) {
        NSMutableArray *selIndexArr = [NSMutableArray array];
        for (int i=0; i<selArr.count; i++) {
            NSNumber *s = selArr[i];
            if ([s boolValue]) {
                [selIndexArr addObject:@(i)];
            }
        }
        if (selIndexArr.count >= 8) {
            
            BOOL canel = NO;
            for (NSNumber *index in selIndexArr) {
                if (indexPath.item==[index integerValue]) {
                    canel = YES;
                    break;
                }
            }
            if (!canel) {
//                [self presentMessageTips:@"最多可选8张"];
                [self presentMessageTips:NSLocalizedString(@"Select no more than 8 pictures", nil)];
                return;
            }
        }
        BOOL sel = [selArr[indexPath.item] boolValue];
        [selArr removeObjectAtIndex:indexPath.item];
        [selArr insertObject:@(!sel) atIndex:indexPath.item];
        
        [collectionView reloadData];
    } else {
        IGArtWorkModel *list = _simiDataArr[indexPath.item];
        XiangQingViewController *vc = [[XiangQingViewController alloc] init];
        vc.p_id = list.aId;
        vc.isRoot = YES;
        [UIViewController ig_pushViewController:vc animated:YES];
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    IGArtWorkModel *f = _simiDataArr[indexPath.item];
    if ([f.plates integerValue]==1)
    {
        //横板
        return CGSizeMake((KSCREENWIDTH-16)/2, ((KSCREENWIDTH-16)/2*1080/1920));
    }
    else if ([f.plates integerValue]==2)
    {
        //坚板
        return CGSizeMake((KSCREENWIDTH-16)/2, ((KSCREENWIDTH-16)/2*1920/1080));
    }
    //批量上传
    else if ([f.plates integerValue] == 3)
    {
        CGFloat scale = [f.imageWidth floatValue]/[f.imageHeight floatValue];
        if (scale > 0)
        {
            if (scale > 16.0/9.0)
            {
                return CGSizeMake((KSCREENWIDTH-16)/2, ((KSCREENWIDTH-16)/2*1080/1920));
            }
            else if (scale < 0.5)
            {
                return CGSizeMake((KSCREENWIDTH-16)/2, (KSCREENWIDTH-16));
            }
            return CGSizeMake((KSCREENWIDTH-16)/2, (KSCREENWIDTH-16)/2/scale);
        }
        return CGSizeMake(0, 0);
    }
    return CGSizeMake(0, 0);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(5, 5, 5, 5);
}

#pragma mark -长按
- (void)longTap:(UIGestureRecognizer *)longTap {
    if (!isEdit) {
        isEdit = YES;
        
        selArr = [NSMutableArray array];
        for (int i=0; i<_simiDataArr.count; i++) {
            [selArr addObject:@(NO)];
        }
        if (self.editBlock) {
            self.editBlock(YES);
        }
        
        if (!tabbar) {
            tabbar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 49)];
            tabbar.backgroundColor = [UIColor whiteColor];
            [self.view addSubview:tabbar];
            
            UIButton *del = [UIButton buttonWithType:UIButtonTypeCustom];
            del.titleLabel.font = [UIFont systemFontOfSize:15];
            [del setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//            [del setTitle:@"删除" forState:UIControlStateNormal];
            [del setTitle:NSLocalizedString(@"Delete", nil) forState:UIControlStateNormal];
            [del setImage:[UIImage imageNamed:@"C-13-3"] forState:UIControlStateNormal];
            [del addTarget:self action:@selector(delModel:) forControlEvents:UIControlEventTouchUpInside];
            [del setImageEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 5)];
            del.frame = CGRectMake(0, 0, KSCREENWIDTH/3, 49);
            [tabbar addSubview:del];
            
            UIButton *push = [UIButton buttonWithType:UIButtonTypeCustom];
            push.backgroundColor = [UIColor appColor];
            push.titleLabel.font = [UIFont systemFontOfSize:15];
            [push setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//            [push setTitle:@"推送到画屏" forState:UIControlStateNormal];
            [push setTitle:NSLocalizedString(@"Push to iGallery", nil) forState:UIControlStateNormal];
            [push addTarget:self action:@selector(pushPhoto:) forControlEvents:UIControlEventTouchUpInside];
            push.frame = CGRectMake(del.right, 0, KSCREENWIDTH/3*2, 49);
            [tabbar addSubview:push];
            
            UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, .5)];
            line.backgroundColor = [UIColor lightGrayColor];
            [tabbar addSubview:line];
        }
        tabbar.top = self.view.height;
        [UIView animateWithDuration:.3 animations:^{
            if ([UIApplication sharedApplication].statusBarFrame.size.height!=20) {
                tabbar.bottom=self.view.height-[UIApplication sharedApplication].statusBarFrame.size.height/2;
            }else{
                tabbar.bottom = self.view.height;
            }
        } completion:^(BOOL finished) {
            collect.mj_header.hidden = YES;
            collect.contentInset = UIEdgeInsetsMake(0, 0, 49*2, 0);
            [collect reloadData];
        }];
    }
}
#pragma mark -删除作品
- (void)delModel:(UIButton *)btn
{
    @KWeakObj(self)
    NSMutableArray *selIndexArr = [NSMutableArray array];
    for (int i=0; i<selArr.count; i++) {
        NSNumber *s = selArr[i];
        if ([s boolValue]) {
            [selIndexArr addObject:@(i)];
        }
    }
    if (selIndexArr.count==0) {
//        [self presentMessageTips:@"至少选择一个作品"];
        [self presentMessageTips:NSLocalizedString(@"Select at least one Work", nil)];
        return;
    }
    NSMutableArray *infoArr = [NSMutableArray array];
    for (NSNumber *index in selIndexArr) {
        info = _simiDataArr[[index integerValue]];
        [infoArr addObject:info.aId];
    }
    p_idsStr = [infoArr componentsJoinedByString:@","];
    
    self.deletApi = [IGdeletWorksApi new];
    [UIAlertView bk_showAlertViewWithTitle:NSLocalizedString(@"Notice", nil) message:NSLocalizedString(@"Confirm to delete this picture/these pictures?",nil) cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:@[NSLocalizedString(@"Confirm", nil)] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            self.deletApi.worksIds = p_idsStr;
            [self.deletApi startWithDecodeClass:[IGdeletWorksResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
                if (responseObject) {
                    [selfWeak canel];
                    [selfWeak firstPage];
                    selfWeak.editBlock(NO);
                }
            }];
        }
    }];
    
}

- (void)hiddenCtrl:(UIControl *)ctrl {
    [UIView animateWithDuration:.3 animations:^{
        ctrl.alpha = 0;
    } completion:^(BOOL finished) {
        [ctrl removeFromSuperview];
    }];
}
#pragma mark -推送作品
- (void)pushPhoto:(UIButton *)btn
{
    NSMutableArray *selIndexArr = [NSMutableArray array];
    for (int i=0; i<selArr.count; i++) {
        NSNumber *s = selArr[i];
        if ([s boolValue]) {
            [selIndexArr addObject:@(i)];
        }
    }
    
    if (selIndexArr.count==0) {
//        [self presentMessageTips:@"至少选择一个作品"];
        [self presentMessageTips:NSLocalizedString(@"Select at least one Work", nil)];
        return;
    }
    
    NSMutableArray *infoArr = [NSMutableArray array];
    for (NSNumber *index in selIndexArr) {
        IGArtWorkModel *work = _simiDataArr[[index integerValue]];
        [infoArr addObject:work];
    }
    
    if (self.iGalleryListArr.count == 0) {
//        [self presentMessageTips:@"当前无绑定设备"];
        [self presentMessageTips:NSLocalizedString(@"No linked device found", nil)];
    } else if (self.iGalleryListArr.count == 1) {
        [self pushToDev:infoArr];
    } else {
        IGPushiGalleryListVC *listVC = [[IGPushiGalleryListVC alloc] initWithType:IGPushiGalleryTypeNN];
        listVC.recommendArr = infoArr;
        listVC.successBlock = ^(NSString *strValue) {
            pushSuccess=strValue;
        };
        [UIViewController ig_pushViewController:listVC animated:YES];
    }
}
- (void)pushToDev:(NSArray *)infoArr
{
    NSMutableArray *aIds = [NSMutableArray array];
    for (IGArtWorkModel *info in infoArr) {
        [aIds addObject:info.aId];
    }
    IGiGalleryEqu *equ = self.iGalleryListArr[0];
    IGiGalleryPushApi *pushApi = [[IGiGalleryPushApi alloc] initWithMacIds:@[equ.macId] pIds:aIds];
//    [self presentMessageTips:@"正在推送..."];
    [self presentMessageTips:NSLocalizedString(@"Pushing...", nil)];
    [pushApi startWithDecodeClass:[IGiGalleryPushResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
//            [self presentMessageTips:@"推送成功..."];
            [self presentMessageTips:NSLocalizedString(@"Pushed Successfully...\n Would show up until device online.", nil)];
            [self canel];
            [self firstPage];
            self.editBlock(NO);
        }
    }];
}
#pragma  mark -请求设备列表
-(void)requestIGlist{
    self.igalleryListApi = [[IGiGalleryListApi alloc] initWithType:IGiGalleryListTypeSuccess];
    __weak typeof(self) weakSelf = self;
    [self.igalleryListApi startWithDecodeClass:[IGiGalleryListResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGiGalleryListResp *resp = responseObject;
            IGiGalleryListModel *model = resp.data;
            weakSelf.iGalleryListArr = [NSArray arrayWithArray:model.equs];
        }
    }];
}
- (void)canel {
    if (isEdit) {
        isEdit=NO;
        [UIView animateWithDuration:.2 animations:^{
            tabbar.top = self.view.height;
        } completion:^(BOOL finished) {
            collect.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
            collect.mj_header.hidden=NO;
            [collect reloadData];
        }];
    }
    else if(isEdit==NO){
        isEdit=YES;
        selArr = [NSMutableArray array];
        for (int i=0; i<_simiDataArr.count; i++) {
            [selArr addObject:@(NO)];
        }
        if (!tabbar) {
            tabbar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 49)];
            tabbar.backgroundColor = [UIColor whiteColor];
            [self.view addSubview:tabbar];
            
            UIButton *del = [UIButton buttonWithType:UIButtonTypeCustom];
            del.titleLabel.font = [UIFont systemFontOfSize:15];
            [del setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//            [del setTitle:@"删除" forState:UIControlStateNormal];
            [del setTitle:NSLocalizedString(@"Delete", nil) forState:UIControlStateNormal];
            [del setImage:[UIImage imageNamed:@"C-13-3"] forState:UIControlStateNormal];
            [del addTarget:self action:@selector(delModel:) forControlEvents:UIControlEventTouchUpInside];
            [del setImageEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 5)];
            del.frame = CGRectMake(0, 0, KSCREENWIDTH/3, 49);
            [tabbar addSubview:del];
            
            UIButton *push = [UIButton buttonWithType:UIButtonTypeCustom];
            push.backgroundColor =[UIColor appColor];
            push.titleLabel.font = [UIFont systemFontOfSize:15];
            [push setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//            [push setTitle:@"推送到画屏" forState:UIControlStateNormal];
            [push setTitle:NSLocalizedString(@"Push to iGallery", nil) forState:UIControlStateNormal];
            [push addTarget:self action:@selector(pushPhoto:) forControlEvents:UIControlEventTouchUpInside];
            push.frame = CGRectMake(del.right, 0, KSCREENWIDTH/3*2, 49);
            [tabbar addSubview:push];
            
            UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, .5)];
            line.backgroundColor = [UIColor lightGrayColor];
            [tabbar addSubview:line];
        }
        tabbar.top = self.view.height;
        [UIView animateWithDuration:.2 animations:^{
            tabbar.bottom = self.view.height;
        } completion:^(BOOL finished) {
            collect.mj_header.hidden = YES;
            collect.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [collect reloadData];
            });
        }];
    }
}

#pragma mark -点击上传私密作品
-(void)mePhoto
{
    [IGPermissionUtil ig_showActionSheetWithCameraBlock:^{
        [IGTakePhotosUtil ig_showImagePickerControllerWithImagePickerBlock:^(NSDictionary<NSString *,id> * _Nullable info)
         {
             UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
             image = [image fixOrientation];
             
             UpPrintVC *vc = [[UpPrintVC alloc] initWithImage:image];
             vc.isOpen = NO;
             [UIViewController ig_pushViewController:vc animated:YES];
         }];
    } photoBlock:^{
        [IGTakePhotosUtil ig_showAssetsForProductPickerControllerWithMaximumNumberOfSelection:8 assetsPickerBlock:^(NSArray<UIImage *> * _Nullable photos, NSArray * _Nullable assets) {
            //选择一张时进入裁剪界面
            dispatch_async(dispatch_get_main_queue(), ^{
                //选择一张时进入裁剪界面
                if (photos.count == 1)
                {
                    UIImage *image = photos[0];
                    UpPrintVC *vc = [[UpPrintVC alloc] initWithImage:image];
                    vc.assets = assets;
                    vc.isOpen = NO;
                    [UIViewController ig_pushViewController:vc animated:YES];
                }
                //选则多张时进入批量上传界面
                else if (photos.count > 1)
                {
                    BatchUploadVC *vc = [[BatchUploadVC alloc] init];
                    vc.assets = [NSMutableArray arrayWithArray:assets];
                    vc.images = [NSMutableArray arrayWithArray:photos];
                    [UIViewController ig_pushViewController:vc animated:YES];
                }
            });
        }];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
